<?php

namespace app\admin\controller;

use think\Request;
//调用model,操作数据库,并取别名
use app\admin\model\User as UserModel;
use app\admin\model\Admin as AdminModel;
use app\admin\model\Shoper as ShoperModel;
use app\admin\model\Area as AreaModel;
use app\admin\model\UserLevel as UserLevelModel;
use app\admin\model\AuthGroup as AuthGroupModel;
use app\admin\model\AuthGroupAccess as AuthGroupAccessModel;

use think\Paginator;
use think\File;
use think\Image;


class Admin extends Base
{
    /*************    管理员管理      ***************/
    //会员列表
    public function lists()
    {
        //遍历用户表,分页
        $user = AdminModel::where(['admin_del'=>0])->paginate(4);
        $userPage = $user->render();
//dump($user);
//dump($userPage);
//dump($data);

        //传值,渲染
        $webSite = WEB_SITE;
        $staticAdmin = STATIC_ADMIN;

        $this->assign([
            'webSite'     => $webSite,
            'staticAdmin' => $staticAdmin,
            'user'        => $user,
            'userPage'    => $userPage,

        ]);

        return $this->fetch();

    }

    //显示用户详情,编辑
    public function edit()
    {
        //获取当前用户信息
        $uid = Request::instance()->param('uid');
        $user = AdminModel::where(['admin_id'=>$uid])->select();

        //遍历全国地址
        $area = AreaModel::all();
        //dump($user);

        //获取值
        $webSite = WEB_SITE;
        $staticAdmin = STATIC_ADMIN;
        foreach ($user as $u) {

            $addr = $u->address;
            //去除首尾下划线,分割字符串,获取省,市,县
            $address = explode('_',trim($addr,'_'));
            //dump($addr);
            //dump($address);
        }

        //传值,渲染
        $this->assign([
            'webSite'     => $webSite,
            'staticAdmin' => $staticAdmin,
            'user'        => $user,
            'area'        => $area,
            'address'     =>  $address,

        ]);
        return $this->fetch();
    }

    //ajax查询(获取单条数据)
    public function sel()
    {
        //根据条件查询
        if (Request::instance()->param('email')) {

            //邮箱
            $email = Request::instance()->param('email');
            $data['admin_email'] = $email;

        } else if (Request::instance()->param('phone')) {

            //手机
            $phone = Request::instance()->param('phone');
            $data['admin_phone'] = $phone;

        } else if (Request::instance()->param('username')) {

            //用户名
            $name = Request::instance()->param('username');
            $data['admin_name'] = $name;
        }

        $data['admin_del'] = 0;
        if (Request::instance()->param('rece') == 1) {
            $data['admin_del'] = 1;
        }
        //查询
        $result = AdminModel::where($data)->select();

        if ($result) {

            //用户
            foreach ($result as $user) {
                //dump($user);
                //防止覆盖
                $data[]['uid'] = $user->admin_id;
                $data[]['pic'] = $user->admin_pic;
                $data[]['username'] = $user->admin_name;
                $data[]['phone'] = $user->admin_phone;
                $data[]['email'] = $user->admin_email;
                $data[]['last_time'] = $user->last_time;
            }

            $active[] =  $user->allow_login == 1 ? '允许' : '禁止';
            $active[] =  $user->admin_id;
            $active[] =  $user->allow_login == 1 ? '&#89;' : 'X';
            // dump($active);
            //dump($levId);
            // dump($user->allow_login);

            //若存在
            if ($user) {

                //获取值
                $webSite = WEB_SITE;
                $staticAdmin = STATIC_ADMIN;

                echo json_encode(['status' => 1,'webSite' => $webSite, 'staticAdmin' => $staticAdmin, 'res' => $data,'active'=>$active]);

            }
        } else {

            echo json_encode(['status'=>2,'tip'=>'您查询的用户不存在']);
        }

    }

    //修改激活标记位
    public function active()
    {
        $uid = Request::instance()->param('uid');
        $active = Request::instance()->param('active');
        $isActive = $active == 1 ? 0 : 1;   //取反

        //当前时间datetime格式
        $currTime = date('Y-m-d H:i:s',time());
        //dump($currTime);

        //修改数据
        $user = AdminModel::where(['admin_id'=>$uid])->update(['allow_login'=>$isActive,'update_time'=>$currTime]);
        //dump($user);
        //dump($isActive);

        if ($user) {
            //更新激活信息
            $active1 =  $isActive == 1 ? '已验证' : '未验证';
            $active2 =  $uid;
            $active3 =  $isActive == 1 ? '&#89;' : 'X';
            $active = [$active1, $active2,$active3];

            //dump($active);
            echo json_encode(['state'=>1,'tip'=>'修改成功','acted'=>$active]);

        } else {
            echo json_encode(['state'=>2,'tip'=>'修改失败']);
        }

    }

    //用户回收
    public function receive()
    {
        //遍历用户表,分页
        $user = AdminModel::where(['admin_del'=>1])->paginate(4);
        $userPage = $user->render();
        /*dump($user);
        dump($userPage);
        die;*/

        //传值,渲染
        $webSite = WEB_SITE;
        $staticAdmin = STATIC_ADMIN;

        $this->assign([
            'webSite'     => $webSite,
            'staticAdmin' => $staticAdmin,
            'user'        => $user,
            'userPage'    => $userPage,
        ]);

        return $this->fetch();

    }

    //添加页面
    public function increase()
    {
        //遍历全国地址
        $area = AreaModel::all();

        //遍历角色(用户组)表
        $authGroup = AuthGroupModel::where(['group_del'=>0])->select();

        //获取值
        $webSite = WEB_SITE;
        $staticAdmin = STATIC_ADMIN;

        //传值,渲染
        $this->assign([
            'webSite'     => $webSite,
            'staticAdmin' => $staticAdmin,
            'area'        => $area,
            'authGroup'   => $authGroup,
        ]);
        return $this->fetch();
    }

    //地址三级联动
    //市级
    public function city()
    {
        $fid = Request::instance()->param('fid');
        $areaTwo = AreaModel::where(['pid'=>$fid])->select();

        echo json_encode(['state'=>1,'city'=>$areaTwo]);

    }

    //县区
    public function country()
    {
        $sid = Request::instance()->param('sid');
        $areaThree = AreaModel::where(['pid'=>$sid])->select();

        echo json_encode(['state'=>2,'country'=>$areaThree]);
    }

    //单图片上传,
    public function upload(){


        //同一个用户一次上传一张
        if (session('pic')) {

            if (Request::instance()->param('hide')) {
                $uid = Request::instance()->param('hide');
                $this->error('你已添加过头像','edit?uid='.$uid);
            } else {
                $this->error('你已添加过头像','increase');
            }
        }
        //获取图片信息
        $file = request()->file('img');

        // 移动到框架应用根目录/public/uploads/ 目录下
        if($file){
            $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads'.DS.'admin');
            if($info){

                // 输出 20160820/42a79759f284b767dfcb2a0197904287.jpg
                //echo $info->getSaveName();
                //将路径保存到全局变量中
                $txPath = 'uploads'.DS.'admin'.DS.$info->getSaveName();
                //截取文件路径,使得同一商品的图片保存在当天的文件夹中
                $pos = strrpos($txPath , '.');
                $path = substr($txPath ,  0 ,$pos);
                //dump($txPath);
                //dump($pos);
                //dump($path);

                $image = Image::open($file);
                // dump($image);

                //拼接生成大,中,小图片文件名
                $txPic = $path .'_txpic.png';

                // 按照比例生成缩略图并保存
                $image->thumb(60, 60)->save($txPic);
                session('pic',$txPic);
                // dump(session('pic'));

                if (Request::instance()->param('hide')) {

                    $uid = Request::instance()->param('hide');
                    $this->success('上传成功','edit?uid='.$uid);

                } else {
                    $this->success('上传成功','increase');
                }

            }else{
                // 上传失败获取错误信息
                // echo json_encode(['status'=>-1, 'path'=>"$err"] );
                $err = $file->getError();
                if (Request::instance()->param('hide')) {

                    $uid = Request::instance()->param('hide');
                    $this->error("$err",'edit?uid='.$uid);
                } else {
                    $this->error("$err",'increase');
                }
            }
        } else {

            if (Request::instance()->param('hide')) {

                $uid = Request::instance()->param('hide');
                $this->error('上传失败,请重新上传','edit?uid='.$uid);
            } else {
                $this->error('上传失败,请重新上传','increase');
            }
        }

    }

    //判断用户名
    public function username()
    {
        $name = Request::instance()->param('username');
        //查询
        $user   = UserModel::where(['username'=>"$name"])->select();
        $admin  = AdminModel::where(['admin_name'=>"$name"])->select();
        $shoper = ShoperModel::where(['shop_name'=>"$name"])->select();

        //判断是否存在数据库
        if ($user || $admin || $shoper) {
            //不存在
            echo json_encode(['status'=>1,'tip'=>'用户名已存在']);
        } else {

            //存在
            echo json_encode(['status'=>2,'tip'=>'用户名合法']);
        }
    }

    //判断邮箱
    public function email()
    {
        $email = Request::instance()->param('email');
        //查询
        $user   = UserModel::where(['email'=>"$email"])->select();
        $admin  = AdminModel::where(['admin_email'=>"$email"])->select();
        $shoper = ShoperModel::where(['shop_email'=>"$email"])->select();

        //判断是否存在数据库
        if ($user || $admin || $shoper) {

            //存在
            echo json_encode(['status'=>3,'tip'=>'邮箱已存在']);
        } else {

            //不存在
            echo json_encode(['status'=>4,'tip'=>'邮箱合法']);
        }
    }

    //判断电话号码
    public function phone()
    {
        $phone = Request::instance()->param('phone');
        //查询
        $user   = UserModel::where(['phone'=>"$phone"])->select();
        $admin  = AdminModel::where(['admin_phone'=>"$phone"])->select();
        $shoper = ShoperModel::where(['shop_phone'=>"$phone"])->select();

        //判断是否存在数据库
        if ($user || $admin || $shoper) {

            //存在
            echo json_encode(['status'=>5,'tip'=>'号码已存在']);
        } else {

            //不存在
            echo json_encode(['status'=>6,'tip'=>'号码合法']);
        }
    }

    //添加用户
    public function add()
    {
        $post  = Request::instance()->param();

        //头像
        if (session('pic')) {
            $data['admin_pic'] = session('pic');
        }

        //获取ip
        $ip1 = $_SERVER['REMOTE_ADDR'];
        //var_dump($ip1);
        if ($ip1 == '::1') {
            $ip1 = '127.0.0.1';
        }
        $ip = ip2long($ip1);
        //var_dump($ip);

        $data['create_ip'] = "$ip";
        $data['admin_password'] = md5($post['password']);
        $data['admin_email']    = $post['email'];
        $data['admin_phone']    = $post['phone'];
        $data['address']  = $post['address'];
        $data['detail_address'] = $post['place'];
        $data['all_place'] = $post['allPlace'];
        //当前时间datetime格式
        $currTime = date('Y-m-d H:i:s',time());
        $data['last_time'] = $currTime;
        $name = $post['username'];
        $data['admin_name'] = $name;

        //查询,防止重复
        $user   = UserModel::where(['username'=>"$name"])->select();
        $admin  = AdminModel::where(['admin_name'=>"$name"])->select();
        $shoper = ShoperModel::where(['shop_name'=>"$name"])->select();

        //判断是否存在数据库
        if ($user || $admin || $shoper) {
            //存在
            echo json_encode(['status'=>1,'tip'=>'用户名已存在','add'=>'重置']);
        } else {

            //插入数据库
            $user = AdminModel::create($data);
            //dump($user);

            //判断是否添加成功
            if (!$user) {

                echo json_encode(['status'=>'11','tip'=>'添加用户失败']);
                //$this->error('添加失败','increase');
            } else {

                //添加用户,角色关联
                $uid = $user->admin_id;
                //dump($uid);
                $data3['admin_id'] = $uid;
                $data3['group_id'] = $post['role'] . ',35';  //默认访问商品
                $res = AuthGroupAccessModel::create($data3);

                //是否成功添加角色
                if (!$res) {

                    echo json_encode(['status'=>1,'tip'=>'添加角色关联失败']);
                } else {

                    //清除上传session
                    if (session('pic')) {
                        session('pic',null);
                    }
                    echo json_encode(['status'=>12,'tip'=>'添加成功']);
                }
            }
        }
    }

    //编辑修改用户信息
    public function update()
    {
        $uid = Request::instance()->param('uid');
        $str = Request::instance()->param('str');
        //dump($str);

        //取出键值对
        $str = trim($str,'"');
        $arr[] = explode('++_++',$str);

        //还原关联数组
        //当前时间datetime格式
        $currTime = date('Y-m-d H:i:s',time());
        //dump($currTime);
        $data['update_time'] = $currTime;

        foreach ($arr as  $value) {

            foreach ($value as $val) {

                $rows = explode('===',$val);
                $data[$rows[0]] = $rows[1];

                //md5加密
                if ($rows[0] == 'admin_password') {

                    $data['admin_password'] = md5($data[$rows[0]]);
                }

            }
        }

        //session图片路径
        if (session('pic')) {
            $data['admin_pic'] = session('pic');
        }
        //dump($rows);
        //dump($data);

        //修改数据
        $user = AdminModel::where(['admin_id'=>$uid])->update($data);
        //dump($user);

        //是否修改成功
        if ($user) {

            //清除头像session
            if (session('pic')) {
                session('pic',null);
            }

            echo json_encode(['status'=>13,'tip'=>'修改成功']);
        } else {
            echo json_encode(['status'=>14,'tip'=>'修改失败']);
        }
    }

    //回收用户(伪删除)
    public function discard()
    {
        $uid = Request::instance()->param('uid');
        $flag = Request::instance()->param('flag');
        //dump($uid);
        //dump($flag);

        $userDel = $flag == 'rever' ? 0 : 1;

        //修改
        //当前时间datetime格式
        $currTime = date('Y-m-d H:i:s',time());

        $user = AdminModel::where(['admin_id'=>$uid])->update(['admin_del'=>$userDel,'update_time'=>$currTime]);
        //dump($user);

        //是否修改
        if ($user) {
            //echo json_encode(['state'=>3,'tip'=>'操作成功']);
            if ($flag == 'rever') {
                $this->success('恢复成功');
            } else if ($flag == 'discard') {
                $this->success('回收成功');
            }

        } else {

            //echo json_encode(['state'=>3,'tip'=>'操作失败']);
            if ($flag == 'rever') {
                $this->error('恢复失败');
            } else if ($flag == 'discard') {
                $this->error('回收失败');
            }
        }
    }

    //删除用户
    public function delete()
    {
        $uid = Request::instance()->param('uid');

        //删除数据库
        $user = AdminModel::where(['admin_id'=>$uid])->delete();
        //dump($user);

        //是否删除成功
        if ($user) {

            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }

    }




}